package cn.spream.common.web;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * web结果集
 * Created with IntelliJ IDEA.
 * User: shaojiaxin
 * Date: 13-8-6
 * Time: 下午10:31
 * To change this template use File | Settings | File Templates.
 */
public class Result {

    //是否成功
    private boolean success;
    //结果集
    private Map<String, Object> attributes = new LinkedHashMap<String, Object>();
    //国际化消息
    private Map<String, Message> messages = new LinkedHashMap<String, Message>();

    public Result(boolean success) {
        this.success = success;
    }

    /**
     * 添加结果
     *
     * @param key
     * @param value
     * @return
     */
    public Result addAttribute(String key, Object value) {
        attributes.put(key, value);
        return this;
    }

    /**
     * 添加消息
     *
     * @param message
     * @return
     */
    public Result addMessage(Message message) {
        String key = message.getKey();
        //key为空则使用code作为key
        if (key == null || key.trim().length() <= 0) {
            key = message.getCode();
        }
        messages.put(key, message);
        return this;
    }

    /**
     * 添加消息
     *
     * @param key
     * @param code
     * @param params
     * @return
     */
    public Result addMessage(String key, String code, String[] params) {
        Message message = new Message(key, code, params);
        return addMessage(message);
    }

    /**
     * 添加消息
     *
     * @param key
     * @param code
     * @return
     */
    public Result addMessage(String key, String code) {
        return addMessage(key, code, new String[0]);
    }

    /**
     * 添加消息
     *
     * @param code
     * @param params
     * @return
     */
    public Result addMessage(String code, String[] params) {
        Message message = new Message(code, params);
        return addMessage(message);
    }

    /**
     * 添加消息
     *
     * @param code
     * @return
     */
    public Result addMessage(String code) {
        Message message = new Message(code, new String[0]);
        return addMessage(message);
    }

    /**
     * 获取所有的消息
     *
     * @return
     */
    public Map<String, Message> getMessages() {
        return messages;
    }

    /**
     * 返回结果集
     *
     * @return
     */
    public Map<String, Object> getAttributes() {
        return attributes;
    }

    /**
     * 返回是否成功
     *
     * @return
     */
    public boolean isSuccess() {
        return success;
    }

    /**
     * 设置是否成功
     *
     * @param success
     */
    public void setSuccess(boolean success) {
        this.success = success;
    }

    /**
     * 根据key获取结果
     *
     * @param key
     * @return
     */
    public Object getAttribute(String key) {
        return attributes.get(key);
    }

    /**
     * 根据key获取string类型的结果
     *
     * @param key
     * @return
     */
    public String getStringAttribute(String key) {
        return String.valueOf(getAttribute(key));
    }

}
